package com.example.demo.utils;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @ClassName LRUCacheLinkedHashMap
 * @Author lys4134
 * @Date 2021/08/03 13:46:29
 * @Description LRUCacheLinkedHashMap
 * @Version 1.0
 **/
public class LRUCacheLinkedHashMap<K, V> extends LinkedHashMap<K, V> {

    /**
     * 定一缓存容量
     */
    private int capacity;

    public LRUCacheLinkedHashMap(int initialCapacity) {
        // AccessOrder = true，则开启了LRU特性
        super(initialCapacity, 0.75f, true);
        this.capacity = initialCapacity;
    }

    @Override
    public V get(Object key) {
        return super.get(key);
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        System.out.println("最早的元素：" + eldest.getKey() + " = " + eldest.getValue());
        return size() > capacity;
    }

    @Override
    public synchronized V put(K key, V value) {
        return super.put(key, value);
    }

    @Override
    public synchronized void putAll(Map<? extends K, ? extends V> m) {
        super.putAll(m);
    }

    public static void main(String[] args) {
        LRUCacheLinkedHashMap cache = new LRUCacheLinkedHashMap(5);
        cache.put("1", "a");
        cache.put("2", "b");
        cache.put("3", "c");
        cache.put("4", "d");
        cache.put("5", "e");
        System.out.println("插入 5 个元素后的顺序");
        printlnCache(cache);
        // 插入第 6 个元素
        cache.put("6", "e");
        System.out.println("插入第 6 个元素后的顺序");
        printlnCache(cache);
        // 访问 第 3 个元素
        cache.get("3");
        System.out.println("访问元素 3 后的顺序");
        printlnCache(cache);
    }

    private static void printlnCache(LRUCacheLinkedHashMap cacheMap) {
        for (Iterator<Map.Entry<String, String>> it = cacheMap.entrySet().iterator(); it.hasNext(); ) {
            System.out.print(it.next().getKey() + "    ");
        }
        System.out.println();
    }

}
